<!DOCTYPE html>

<html>
<head>
<title>Password Match</title>

<script>
    function checkPasswords() {
        var pass1 = document.getElementById("password1");
        var pass2 = document.getElementById("password2");

        if (pass1.value != pass2.value)
            pass1.setCustomValidity("Your passwords do not match. Please recheck that your
            new password is entered identically in the two fields.");
        else
            pass1.setCustomValidity("");
    }


    function invalidHandler(evt) {
        // set the label's text color to red
        evt.srcElement.style.background = 'red';

        // stop the event from propagating higher
        evt.stopPropagation();

        // stop the browser's default handling of the validation error
        evt.preventDefault();
    }

    function loadDemo() {
       // register an event handler on the form to
       // handle all invalid control notifications
       document.passwordChange.addEventListener("invalid", invalidHandler, true);
    }

    window.addEventListener("load", loadDemo, false);
</script>

</head>

<body>
<form name="passwordChange">
    <p><label for="password1">New Password:</label>
    <input type="password" id="password1" onchange="checkPasswords()"></p>
    <p><label for="password2">Confirm Password:</label>
    <input type="password" id="password2" onchange="checkPasswords()"></p>
</form>
<button onclick="document.passwordChange.password1.checkValidity()">Check Validity</button>

</body>
</html>